package cn.sharkandlookaround.com.uetokensdk;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

/**
 * @author xie
 * @time 2018/10/30 10:52
 * @class 描述:PCN授权帮助类
 */
public class UETokenHelper {
    private static Context mContext;
    /**
     * 跳转回去的规则(授权)
     */
    private static String AuthorizationHost;
    /**
     * 跳转回去的规则(pcn支付)
     */
    private static String uePayHost;
    /**
     * 分配给第三方的key
     */
    private static String secretkey;
    /**
     * 充值金额
     */
    private static String amount;
    /**
     * 订单号
     */
    private static String orderno;
    /**
     * 商品名称
     */
    private static String subject;
    /**
     * 商品描述
     */
    private static String body;
    /**
     * 支付信息
     */
    private static String json;
    /**
     * 通知Url
     */
    private static String noticeurl;
    private static GetAuthorizationInfoListener mGetInfoListener;
    private static GetUEPayInfoListener mUEPayInfoListener;
    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) SPUtils.get(mContext, "uetoken_sdk_verification_key_data", "");
            if (TextUtils.isEmpty(data)) {
                data = (String) msg.obj;
            }
//            String data = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(data);
                int code = jsonObject.getInt("Success");
                String message = jsonObject.getString("Message");
                String storeName = jsonObject.getString("Storename");
                String logo = jsonObject.getString("Logo");
                switch (msg.what) {
                    case 10:
                        //ue授权
                        if (code == 1) {
                            Intent intent = new Intent();
                            intent.setData(Uri.parse("ue://" + AuthorizationHost + "?actionType=7000&storeName=" + storeName + "&logo=" + logo));
                            mContext.startActivity(intent);
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 20:
                        //ue支付
                        if (code == 1) {
                            Intent intent = new Intent();
                            intent.setData(Uri.parse("ue://" + uePayHost + "?actionType=8000" + "&json=" + json));
//                            intent.setData(Uri.parse("ue://" + pcnPayHost + "?actionType=8000" + "&secretkey=" + secretkey + "&amount=" + amount + "&orderno=" + orderno + "&subject=" + subject + "&body=" + body + "&noticeurl=" + noticeurl + "&storeName=" + storeName + "&logo=" + logo));
                            mContext.startActivity(intent);
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 30:
                        boolean isVerication = false;
                        if (code == 1) {
                            isVerication = true;
                        } else {
                            isVerication = false;
                        }
                        SPUtils.put(mContext, "uetoken_sdk_isverification", isVerication);
                        break;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };


    /**
     * 验证key是否正确
     *
     * @param key
     */
    private static void verificationKey(final String key) {

//        if (isApplicationAvilible(mContext, "com.uetoken.cn")) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader reader = null;
                try {
                    URL httpUrl = new URL("http://client.p.cn/AppService.asmx/ThirdPartyVerify?secretkey=" + key);
                    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                    conn.setReadTimeout(5000);
                    //设置请求方式为GET
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        final StringBuffer sb = new StringBuffer();
                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        String data = sb.toString();
                        int start = data.indexOf("{");
                        int end = data.indexOf("}");
                        data = data.substring(start, end + 1);

                        SPUtils.put(mContext, "uetoken_sdk_verification_key_data", data);

                        mHandler.obtainMessage(30, data).sendToTarget();

                    }

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }).start();

//        } else {
//            Toast.makeText(mContext, "未安装Pcn客户端", Toast.LENGTH_SHORT).show();
//        }
    }


    public static void init(Context context, String AppKey, String Channel, boolean isDebug) {
        mContext = context;
        verificationKey(AppKey);
        SPUtils.put(context, "uetoken_sdk_channel", Channel);
        SPUtils.put(context, "uetoken_sdk_isdebug", isDebug);
    }

    /**
     * 跳转UE授权
     *
     * @param getInfoListener 获取UE授权成功后返回相关信息的回调函数
     * @param host            自己定义的相关应用间跳转的规则
     */
    public static void toAuthorization(Context context, GetAuthorizationInfoListener getInfoListener, String host) {
        mContext = context;
        boolean isVerication = (boolean) SPUtils.get(mContext, "uetoken_sdk_isverification", false);
        if (isVerication) {
            if (isApplicationAvilible(mContext, "com.uetoken.cn")) {
                mGetInfoListener = getInfoListener;
                AuthorizationHost = host;
                mHandler.obtainMessage(10, "").sendToTarget();
            } else {
                Toast.makeText(mContext, mContext.getString(R.string.no_install), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.initialize_failed), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取授权者信息
     *
     * @param uri 授权成功后需要将此uri传递给sdk,sdk解析此uri后将信息传递给调用者
     */
    public static void getAuthorizationInfo(Uri uri) {
//        boolean isVerication = (boolean) SPUtils.get(mContext, "uetoken_sdk_isverification", false);
//        if (isVerication) {
        if (uri != null) {
            String actionType = uri.getQueryParameter("actionType");
            if (Integer.parseInt(actionType) == 7000 || Integer.parseInt(actionType) == 6000) {
                String nodeName = uri.getQueryParameter("nodeName");
                String nodeId = uri.getQueryParameter("nodeId");
                String nodeCode = uri.getQueryParameter("nodeCode");
                if (mGetInfoListener != null) {
                    //将需要的信息传递给用户
                    mGetInfoListener.success(nodeName, nodeId, nodeCode);
                }
            } else {
                int code = Integer.parseInt(uri.getQueryParameter("returnCode"));
                String message = uri.getQueryParameter("returnMessage");
                if (mGetInfoListener != null) {
                    mGetInfoListener.fail(code, message);
                }
            }
        }
//        } else {
//            Toast.makeText(mContext, "UE Token SDK 初始化失败", Toast.LENGTH_SHORT).show();
//        }
    }

    /**
     * @param context           上下文
     * @param UEPayInfoListener 支付回调函数
     * @param jsonData          支付信息
     */
    public static void toUETokenPay(Context context, GetUEPayInfoListener UEPayInfoListener, String host, String jsonData) {
        mContext = context;
        boolean isVerication = (boolean) SPUtils.get(mContext, "uetoken_sdk_isverification", false);
        if (isVerication) {
            if (isApplicationAvilible(mContext, "com.uetoken.cn")) {
                mUEPayInfoListener = UEPayInfoListener;
                uePayHost = host;
                json = jsonData;
                mHandler.obtainMessage(20, "").sendToTarget();
            } else {
                Toast.makeText(mContext, mContext.getString(R.string.no_install), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.initialize_failed), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取支付成功后的信息
     *
     * @param uri
     */
    public static void getUEPayReturnInfo(Uri uri) {
        //{"data":{"orderno":"3938","ordernoue":"1843"},"result":1,"message":"成功"}
        if (uri != null) {
            String actionType = uri.getQueryParameter("actionType");
            //支付成功
            if (Integer.parseInt(actionType) == 8000 || Integer.parseInt(actionType) == 3001) {
                String result;
                int resultCode = -1;
                String orderno = "";
                String ordernoue = "";
                String message = "";
                if (Integer.parseInt(actionType) == 3001) {
                    String json = uri.getQueryParameter("json");
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        resultCode = jsonObject.getInt("result");
                        message = jsonObject.getString("message");
                        String data = jsonObject.getString("data");
                        JSONObject jsonData = new JSONObject(data);
                        orderno = jsonData.getString("orderno");
                        ordernoue = jsonData.getString("ordernoue");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    result = uri.getQueryParameter("result");
                    resultCode = Integer.parseInt(result);
                    orderno = uri.getQueryParameter("orderno");
                    ordernoue = uri.getQueryParameter("ordernoue");
                    message = uri.getQueryParameter("message");
                }
//                //第三方订单号
//                String orderNumber = uri.getQueryParameter("orderno");
//                //UE订单号
//                String orderPcn = uri.getQueryParameter("OrderPcn");
                if (mUEPayInfoListener != null) {
                    mUEPayInfoListener.getPayInfoSuccess(resultCode, orderno, ordernoue, message);
                }
            } else {
                //支付失败
//                int code = Integer.parseInt(uri.getQueryParameter("returnCode"));
                String message = uri.getQueryParameter("message");
                if (mUEPayInfoListener != null) {
                    mUEPayInfoListener.getPayInfoFail(1000, message);
                }
            }
        }
    }

    /**
     * 判断手机是否安装某个应用
     *
     * @param context
     * @param appPackageName 应用包名
     * @return true：安装，false：未安装
     */
    private static boolean isApplicationAvilible(Context context, String appPackageName) {
        // 获取packagemanager
        PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (appPackageName.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }


}
